import React, {useEffect, useRef, useState} from 'react';
import type { ProFormInstance} from "@ant-design/pro-form";
import {ModalForm} from "@ant-design/pro-form";
import {ProFormMoney, ProFormText} from "@ant-design/pro-form";
import dayjs from "dayjs";
import type {PaymentLogItem} from "@/pages/PaymentLogs/data";
import {queryFamily, queryPayment} from "@/pages/User/Account/settings/components/service";
import {Col, Row} from "antd";
import {DatePicker, Selector} from "antd-mobile";

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<PaymentLogItem>;

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  modalVisible: boolean;
  values: Partial<PaymentLogItem>;
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [defaultType, setDefaultType] = useState<string[]>([])
  const [defaultUseBy, setDefaultUseBy] = useState<string[]>([])

  useEffect(()=>{
    if (props.values){
      formRef.current?.setFieldsValue({
        payTypeId: props.values.payType?.id,
        familyTypeId: props.values.familyType?.id,
      })
    }

    if (props.values.payType){
      setDefaultType([props.values.payType?.id])
    }

    if (props.values.familyType){
      setDefaultUseBy([props.values.familyType?.id])
    }

  }, [props.values])

  // const formItemLayout ={
  //   labelCol: { span: 6 },
  //   wrapperCol: { span: 18 },
  // }

  // 支出分类options
  const [typeDataSource, setTypeDatasource] = useState<any[]>([])

  // 从后台获取支出分类数据
  useEffect(() => {
    queryPayment().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        const data = [...typeDataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: any)=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setTypeDatasource(data)
      }
    })
  }, []);

  const [useBydataSource, setUseByDatasource] = useState<any[]>([])

  // 从后台获取用户对象数据
  useEffect(() => {
    queryFamily().then((res)=>{
      if (res.status === "done"){
        // 数据获取成功
        // 整理list为prolist对象
        const data = [...useBydataSource];

        // 先清空
        data.splice(0, data.length)

        // 填充新数据
        // eslint-disable-next-line array-callback-return
        res.data?.map((item: any)=>{
          data.push({
            label: item.name,
            value: item.id,
          })
        })
        setUseByDatasource(data)
      }
    })
  }, []);

  // 移动端日期选择器
  const [timePickerVisible, setTimePickerVisible] = useState<boolean>(false)

  return (
    <ModalForm
      title={"修改支出流水"}
      visible={props.modalVisible}
      width={650}
      formRef={formRef}
      // Drawer抽屉需要关联上层UpdateForm的点击管理函数
      onFinish={props.onSubmit}
      modalProps={{
        destroyOnClose: true,
        // 抽屉层关闭函数， 需要关联上层的onCancel函数
        onCancel: function (){
          props.onCancel()
        },
      }}
    >
      <ProFormText
        name={"payTypeId"}
        hidden
      />
      <ProFormText
        name={"familyTypeId"}
        hidden
      />
      <ProFormMoney
        name={"money"}
        label={"金额"}
        placeholder={"0.00"}
        initialValue={props.values.money}
        rules={[{required:true, message:'金额必填！'}]}
      />
      <ProFormText
        hidden
        name={"time"}
      />
      <ProFormText
        label={"时间"}
        name={"timeStr"}
        initialValue={`${dayjs(props.values.time).format("YYYY-MM-DD HH:mm")}`}
        fieldProps={{
          onClick: ()=>{
            setTimePickerVisible(true)
          }
        }}
      />
      <DatePicker
        visible={timePickerVisible}
        precision='minute'
        onCancel={()=>{
          setTimePickerVisible(false)
        }}
        onConfirm={(val)=>{
          formRef.current?.setFieldsValue({
            time: dayjs(val).utc().format(),
            timeStr: dayjs(val).format("YYYY-MM-DD HH:mm")
          })
          setTimePickerVisible(false)
        }}
      />
      {/*<ProFormDateTimePicker*/}
      {/*  name={"time"}*/}
      {/*  label={"时间"}*/}
      {/*  initialValue={`${dayjs(props.values.time).utc().format()}`}*/}
      {/*  fieldProps={{*/}
      {/*    style: {"width": "100%"},*/}
      {/*    onChange : (value) => {*/}
      {/*      formRef.current?.setFieldsValue({*/}
      {/*        // @ts-ignore*/}
      {/*        time: dayjs(value).utc().format()*/}
      {/*      })*/}
      {/*    }*/}
      {/*  }}*/}
      {/*/>*/}
      <Row style={{marginBottom: 10}}>
        <span style={{marginBottom: 8}}>支出分类</span>
        <Col span={24}>
          <Selector
            key={Date.now()}
            columns={5}
            options={typeDataSource}
            defaultValue={defaultType}
            multiple={false}
            showCheckMark={false}
            style={{
              '--checked-color': "#fa541c",
              '--checked-text-color': "white",
              '--gap': "3px",
            }}
            onChange={(value)=>{
              formRef.current?.setFieldsValue({
                payTypeId: value[0]
              })
            }}
          />
        </Col>
      </Row>
      <Row style={{marginBottom: 10}}>
        <span style={{marginBottom: 8}}>支出对象</span>
        <Col span={24}>
          <Selector
            key={Date.now()}
            columns={5}
            options={useBydataSource}
            defaultValue={defaultUseBy}
            multiple={false}
            showCheckMark={false}
            style={{
              '--checked-color': "#fa541c",
              '--checked-text-color': "white",
              '--gap': "3px",
            }}
            onChange={(value)=>{
              formRef.current?.setFieldsValue({
                familyTypeId: value[0]
              })
            }}
          />
        </Col>
      </Row>
      <ProFormText
        name={"remark"}
        label={"备注"}
        initialValue={props.values.remark}
        placeholder={"请输入备注"}
      />
    </ModalForm>
  );
};

export default UpdateForm;
